<?php
/**
 * 1. SMTP Send one mail:
 * $mail = new Mail();
 * ...
 * $mail->send();
 * 
 * 2. SMTP Send several mails:
 * $mail = new Mail();
 * ...
 * $mail->auto_close = false;
 * $mail->send();
 * $mail->reset();
 * $mail->setTo(...);
 * $mail->setHtml(...);
 * $mail->send();
 * ...
 * $mail->close();
 */
class Mail {
	protected $to;
	protected $from;
	protected $sender;
	protected $subject;
	protected $text;
	protected $html;
	protected $attachments = array();
	protected $smtp = null;
	//mail or smtp
	public $protocol = 'mail';
	public $hostname;
	public $username;
	public $password;
	public $port = 25;
	public $timeout = 5;
	public $auto_close = true;
	public $newline = "\n";
	public $crlf = "\r\n";
	public $verp = false;
	public $parameter = '';
	public $error = null;

	public function setTo($to) {
		$this->to = $to;
	}

	public function setFrom($from) {
		$this->from = $from;
		$this->sender = $from;
	}

	public function setSender($sender) {
		$this->sender = $sender;
	}

	public function setSubject($subject) {
		$this->subject = $subject;
	}

	public function setText($text) {
		$this->text = $text;
	}

	public function setHtml($html) {
		$this->html = $html;
	}

	public function addAttachment($filename) {
		$this->attachments[] = $filename;
	}

	public function send() {
		if (!$this->to) {
			trigger_error('Error: E-Mail to required!');
			exit();
		}

		if (!$this->from) {
			trigger_error('Error: E-Mail from required!');
			exit();
		}

		if (!$this->subject) {
			trigger_error('Error: E-Mail subject required!');
			exit();
		}

		if ((!$this->text) && (!$this->html)) {
			trigger_error('Error: E-Mail message required!');
			exit();
		}

		if (is_array($this->to)) {
			$to = implode(',', $this->to);
		} else {
			$to = $this->to;
		}

		$boundary = '----=_NextPart_' . md5(time());

		$header = '';

		$header .= 'MIME-Version: 1.0' . $this->newline;

		if ($this->protocol != 'mail') {
			$header .= 'To: ' . $to . $this->newline;
			$header .= 'Subject: ' . $this->subject . $this->newline;
		}

		$header .= 'Date: ' . date('D, d M Y H:i:s O') . $this->newline;
		$header .= 'From: ' . '=?UTF-8?B?' . base64_encode($this->sender) . '?=' . '<' . $this->from . '>' . $this->newline;
		$header .= 'Reply-To: ' . '=?UTF-8?B?' . base64_encode($this->sender) . '?=' . '<' . $this->from . '>' . $this->newline;
		$header .= 'Return-Path: ' . $this->from . $this->newline;
		$header .= 'X-Mailer: PHP/' . phpversion() . $this->newline;
		$header .= 'Content-Type: multipart/related; boundary="' . $boundary . '"' . $this->newline . $this->newline;

		if (!$this->html) {
			$message  = '--' . $boundary . $this->newline;
			$message .= 'Content-Type: text/plain; charset="utf-8"' . $this->newline;
			$message .= 'Content-Transfer-Encoding: 8bit' . $this->newline . $this->newline;
			$message .= $this->text . $this->newline;
		} else {
			$message  = '--' . $boundary . $this->newline;
			$message .= 'Content-Type: multipart/alternative; boundary="' . $boundary . '_alt"' . $this->newline . $this->newline;
			$message .= '--' . $boundary . '_alt' . $this->newline;
			$message .= 'Content-Type: text/plain; charset="utf-8"' . $this->newline;
			$message .= 'Content-Transfer-Encoding: 8bit' . $this->newline . $this->newline;

			if ($this->text) {
				$message .= $this->text . $this->newline;
			} else {
				$message .= 'This is a HTML email and your email client software does not support HTML email!' . $this->newline;
			}

			$message .= '--' . $boundary . '_alt' . $this->newline;
			$message .= 'Content-Type: text/html; charset="utf-8"' . $this->newline;
			$message .= 'Content-Transfer-Encoding: 8bit' . $this->newline . $this->newline;
			$message .= $this->html . $this->newline;
			$message .= '--' . $boundary . '_alt--' . $this->newline;
		}

		foreach ($this->attachments as $attachment) {
			if (file_exists($attachment)) {
				$handle = fopen($attachment, 'r');

				$content = fread($handle, filesize($attachment));

				fclose($handle);

				$message .= '--' . $boundary . $this->newline;
				$message .= 'Content-Type: application/octet-stream; name="' . basename($attachment) . '"' . $this->newline;
				$message .= 'Content-Transfer-Encoding: base64' . $this->newline;
				$message .= 'Content-Disposition: attachment; filename="' . basename($attachment) . '"' . $this->newline;
				$message .= 'Content-ID: <' . basename(urlencode($attachment)) . '>' . $this->newline;
				$message .= 'X-Attachment-Id: ' . basename(urlencode($attachment)) . $this->newline . $this->newline;
				$message .= chunk_split(base64_encode($content));
			}
		}

		$message .= '--' . $boundary . '--' . $this->newline;

		if ($this->protocol == 'mail') {
			ini_set('sendmail_from', $this->from);

			if ($this->parameter) {
				return @mail($to, '=?UTF-8?B?' . base64_encode($this->subject) . '?=', $message, $header, $this->parameter);
			} else {
				return @mail($to, '=?UTF-8?B?' . base64_encode($this->subject) . '?=', $message, $header);
			}
		} elseif ($this->protocol == 'smtp') {
			//connect
			if (!$this->smtp) {
				if(!$this->connect()) {
					return false;
				}
			}

			//mail from
			if ($this->verp) {
				fputs($this->smtp, 'MAIL FROM: <' . $this->from . '>XVERP' . $this->crlf);
			} else {
				fputs($this->smtp, 'MAIL FROM: <' . $this->from . '>' . $this->crlf);
			}

			$line = fgets($this->smtp, 512);

			if (substr($line, 0, 3) != 250) {
				$this->error = "MAIL FROM: $line";
				return false;;
			}

			//rcpt to
			if (!is_array($this->to)) {
				fputs($this->smtp, 'RCPT TO: <' . $this->to . '>' . $this->crlf);
				$line = fgets($this->smtp, 512);
				if (substr($line, 0, 3) != 250 && substr($line, 0, 3) != 251) {
					$this->error = "RCPT TO (1): $line";
					return false;
				}
			} else {
				foreach ($this->to as $recipient) {
					fputs($this->smtp, 'RCPT TO: <' . $recipient . '>' . $this->crlf);
					$line = fgets($this->smtp, 512);
					if (substr($line, 0, 3) != 250 && substr($line, 0, 3) != 251) {
						$this->error = "RCPT TO (2): $line";
						return false;
					}
				}
			}

			//data
			fputs($this->smtp, 'DATA' . $this->crlf);

			$line = fgets($this->smtp, 512);

			if (substr($line, 0, 3) != 354) {
				$this->error = "DATA (1): $line";
				return false;
			}

			// According to rfc 821 we should not send more than 1000 including the CRLF
			$message = str_replace("\r\n", "\n",  $header . $message);
			$message = str_replace("\r", "\n", $message);

			$lines = explode("\n", $message);

			foreach ($lines as $line) {
				$results = str_split($line, 998);

				foreach ($results as $result) {
					if (substr(PHP_OS, 0, 3) != 'WIN') {
						fputs($this->smtp, $result . $this->crlf);
					} else {
						fputs($this->smtp, str_replace("\n", "\r\n", $result) . $this->crlf);
					}
				}
			}

			fputs($this->smtp, '.' . $this->crlf);

			$line = fgets($this->smtp, 512);

			if (substr($line, 0, 3) != 250) {
				$this->error = "DATA (2): $line";
				return false;
			}
			
			if ($this->auto_close) $this->close();
			
			return true;
		}
	}

	protected function connect() {
		$this->smtp = fsockopen($this->hostname, $this->port, $errno, $errstr, $this->timeout);
		if (!$this->smtp) {
			$this->error = "$errno : $errstr";
			return false;
		}
		stream_set_blocking($this->smtp, true);
		
		if (substr(PHP_OS, 0, 3) != 'WIN') {
			socket_set_timeout($this->smtp, $this->timeout, 0);
		}

		$line = fgets($this->smtp, 512);
		if(substr($line, 0, 3) != '220') {
			$this->error = "CONNECT: $line";
			return false;
		}
		
		if (substr($this->hostname, 0, 3) == 'tls') {
			fputs($this->smtp, 'STARTTLS' . $this->crlf);
			$line = fgets($this->smtp, 512);
			if (substr($line, 0, 3) != 220) {
				$this->error = "STARTTLS: $line";
				return false;
			}
		}

		if (!empty($this->username)  && !empty($this->password)) {
			fputs($this->smtp, 'EHLO PHPMail' . $this->crlf);

			$line = fgets($this->smtp, 512);
			if (substr($line, 0, 3) != 250) {
				$this->error = "EHLO: $line";
				return false;
			}

			while(1) {
				if(substr($line, 3, 1) != '-' || empty($line)) break;
				$line = fgets($this->smtp, 512);
			}
			
			fputs($this->smtp, 'AUTH LOGIN' . $this->crlf);

			$line = fgets($this->smtp, 512);
			if (substr($line, 0, 3) != 334) {
				$this->error = "AUTH LOGIN: $line";
				return false;
			}

			fputs($this->smtp, base64_encode($this->username) . $this->crlf);

			$line = fgets($this->smtp, 512);
			if (substr($line, 0, 3) != 334) {
				$this->error = "Error: $line";
				return false;
			}

			fputs($this->smtp, base64_encode($this->password) . $this->crlf);

			$line = fgets($this->smtp, 512);
			if (substr($line, 0, 3) != 235) {
				$this->error = "Error: $line";
				return false;
			}
		} else {
			fputs($this->stmp, 'HELO PHPMail' . $this->crlf);

			$line = fgets($this->smtp, 512);

			if (substr($line, 0, 3) != 250 && substr($line, 0, 3) != 220) {
				$this->error = "HELO $line";
				return false;
			}
		}
		return true;
	}
	
	public function reset() {
		if (!$this->smtp) return;
		
		fputs($this->smtp, "RSET\r\n");
		$line = fgets($this->smtp, 512);
		if(substr($line, 0, 3) != 250) {
			$this->error = "REST: $line";
			return false;
		}
		
		$this->error = null;
		
		return true;
	}
	
	public function close() {
		if (!$this->smtp) return;
		
		fputs($this->smtp, 'QUIT' . $this->crlf);
		$line = fgets($this->smtp, 512);
		if (substr($line, 0, 3) != 221) {
			$this->error = "QUIT: $line";
		}

		return fclose($this->smtp);
	}
}